﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;

using SIPO.Library;
using SIPO.Library.DomainObject.Administration.Catalog;
using SIPO.Library.Enum;
using SIPO.Library.Interfaces;

namespace SIPO.Library.DataAccess.Administration.Catalog
{
    public partial class DepartmentRepo : ISearchable<Department>
    {
        public object SelectScalar(SQL.Function.Aggregate function, string column,string parameters)
        {
            object _result = null;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    StringBuilder sbQuery = new StringBuilder();
                    switch (function)
                    {
                        case SQL.Function.Aggregate.Max:
                            sbQuery.AppendFormat("SELECT MAX({0}) FROM master.Department", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Min:
                            sbQuery.AppendFormat("SELECT MIN({0}) FROM master.Department", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Distinct:
                            sbQuery.AppendFormat("SELECT DISTINCT({0}) FROM master.Department", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Count:
                            sbQuery.AppendFormat("SELECT COUNT({0}) FROM master.Department", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Sum:
                            sbQuery.AppendFormat("SELECT SUM({0}) FROM master.Department", column, parameters);
                            break;
                        case SQL.Function.Aggregate.Avg:
                            sbQuery.AppendFormat("SELECT AVG({0}) FROM master.Department", column, parameters);
                            break;
                        default:
                            // do nothing 
                            break;
                    }

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        _result = cmd.ExecuteScalar();
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return _result;
        }

        public List<Department> GetList(int pageSize, int currentPage, string sortName, string sortOrder, string parameters)
        {
            List<Department> tt = new List<Department>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    int startRow = ((currentPage - 1) * pageSize) + 1;
                    int endRow = (startRow + pageSize);

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" WITH result_set AS ");
                    sbQuery.AppendFormat(" ( ");
                    sbQuery.AppendFormat("    SELECT ");
                    sbQuery.AppendFormat("      ROW_NUMBER() OVER (ORDER BY {0} {1}) AS [row_number], ", sortName, sortOrder);
                    sbQuery.AppendFormat("      DeptID, RowStatus, DepartmentDesc, CreatedBy, CreatedDate, UpdatedDate, UpdatedBy ");
                    sbQuery.AppendFormat("    FROM ");
                    sbQuery.AppendFormat("      master.Department ");
                    sbQuery.AppendFormat("    {0}", parameters);
                    sbQuery.AppendFormat(" ) ");
                    sbQuery.AppendFormat(" SELECT * FROM result_set WHERE [row_number] BETWEEN {0} AND {1} ", startRow, endRow);

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                Department t = new Department();
                                t.DeptID = dr[Department.Fields.DeptID] == DBNull.Value ? 0 : int.Parse(dr[Department.Fields.DeptID].ToString());
                                t.RowStatus = dr[Department.Fields.RowStatus] == DBNull.Value ? false : bool.Parse(dr[Department.Fields.RowStatus].ToString());
                                t.DepartmentDesc = dr[Department.Fields.DepartmentDesc] == DBNull.Value ? string.Empty : dr[Department.Fields.DepartmentDesc].ToString();
                                t.CreatedBy = dr[Department.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[Department.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[Department.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Department.Fields.CreatedDate].ToString());
                                t.UpdatedDate = dr[Department.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Department.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[Department.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[Department.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public List<Department> GetListByPositionID(int positionID)
        {
            List<Department> tt = new List<Department>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT A.DeptID, A.RowStatus, A.DepartmentDesc, A.CreatedBy, A.CreatedDate, A.UpdatedDate, A.UpdatedBy
                                      FROM master.Department A INNER JOIN master.Position B ON A.DeptID = B.DepartmentID WHERE B.PositionID = @PositionID ";
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@PositionID", SqlDbType.Int).Value = positionID;

                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                Department t = new Department();
                                t.DeptID = dr[Department.Fields.DeptID] == DBNull.Value ? 0 : int.Parse(dr[Department.Fields.DeptID].ToString());
                                t.RowStatus = dr[Department.Fields.RowStatus] == DBNull.Value ? false : bool.Parse(dr[Department.Fields.RowStatus].ToString());
                                t.DepartmentDesc = dr[Department.Fields.DepartmentDesc] == DBNull.Value ? string.Empty : dr[Department.Fields.DepartmentDesc].ToString();
                                t.CreatedBy = dr[Department.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[Department.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[Department.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Department.Fields.CreatedDate].ToString());
                                t.UpdatedDate = dr[Department.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Department.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[Department.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[Department.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }

        public DataTable GetDataTableReport()
        {
            DataTable dt = new DataTable();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {

                    StringBuilder sbQuery = new StringBuilder();

                    sbQuery.AppendLine("SELECT   ROW_NUMBER() OVER(ORDER BY DepartmentDesc ASC) AS No,DepartmentDesc Nama");
                    sbQuery.AppendLine("FROM  master.Department ORDER BY DepartmentDesc ASC ");
                   
                    cmd.CommandText = sbQuery.ToString();

                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = cmd;

                    try
                    {
                        conn.Open();
                        da.Fill(dt);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }

                }
            }

            return dt;

        }

        public string GetDeptIDByLogin(string positionID)
        {
            string result = string.Empty;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                  

                    StringBuilder sbQuery = new StringBuilder();
                    sbQuery.AppendFormat(" SELECT DepartmentID");
                    sbQuery.AppendFormat(" FROM master.Position ");
                    sbQuery.AppendFormat(" WHERE PositionID IN {0}",positionID);
                    sbQuery.AppendFormat(" GROUP BY  DepartmentID");

                    cmd.CommandText = sbQuery.ToString();
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                result += dr[Position.Fields.DepartmentID] == DBNull.Value ? string.Empty : dr[Position.Fields.DepartmentID].ToString()+",";
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }

            
            return result;
        }

        public List<Department> GetListWhereClauseINID(string deptID)
        {
            List<Department> tt = new List<Department>();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT DeptID, RowStatus, DepartmentDesc, CreatedBy, CreatedDate, UpdatedDate, UpdatedBy FROM master.Department WHERE DeptID IN "+deptID;
                    cmd.CommandType = CommandType.Text;
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                        {
                            while (dr.Read())
                            {
                                Department t = new Department();
                                t.DeptID = dr[Department.Fields.DeptID] == DBNull.Value ? 0 : int.Parse(dr[Department.Fields.DeptID].ToString());
                                t.RowStatus = dr[Department.Fields.RowStatus] == DBNull.Value ? false : bool.Parse(dr[Department.Fields.RowStatus].ToString());
                                t.DepartmentDesc = dr[Department.Fields.DepartmentDesc] == DBNull.Value ? string.Empty : dr[Department.Fields.DepartmentDesc].ToString();
                                t.CreatedBy = dr[Department.Fields.CreatedBy] == DBNull.Value ? string.Empty : dr[Department.Fields.CreatedBy].ToString();
                                t.CreatedDate = dr[Department.Fields.CreatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Department.Fields.CreatedDate].ToString());
                                t.UpdatedDate = dr[Department.Fields.UpdatedDate] == DBNull.Value ? (DateTime?)null : DateTime.Parse(dr[Department.Fields.UpdatedDate].ToString());
                                t.UpdatedBy = dr[Department.Fields.UpdatedBy] == DBNull.Value ? string.Empty : dr[Department.Fields.UpdatedBy].ToString();
                                tt.Add(t);
                                t.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (conn.State == ConnectionState.Open) conn.Close();
                    }
                }
            }
            return tt;
        }		


    }
}
